<template>
  <div class="m-teach-base-info">
    <div class="m-h3-btn-box border">
      <h3>教学信息</h3>
      <div class="u-btn-box">
        <el-button type="primary" @click="teachingSave()" size="small">
          {{ isTeachingSave ? '保存' : '编辑' }}</el-button
        >
      </div>
    </div>
    <el-form
      :model="teaching"
      label-width="150px"
      label-position="right"
      :rules="teachingRules"
      ref="teaching"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="教学经验（年）：" prop="year_of_work">
            <el-input
              v-model="teaching.year_of_work"
              placeholder="请输入教学经验"
              clearable
              :disabled="!isTeachingSave"
              maxlength="2"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="讲师评级：" prop="speaker_rating">
            <nice-select
              v-model="teaching.speaker_rating"
              placeholder="请选择讲师评级"
              clearable
              :disabled="!isTeachingSave"
              :options="selectEnums.speaker_rating"
            ></nice-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="主讲年级：" prop="speaker_grade">
            <nice-select
              v-model="teaching.speaker_grade"
              placeholder="请选择主讲年级"
              clearable
              :disabled="!isTeachingSave"
              :options="selectEnums.speaker_grade"
            ></nice-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="主讲科目：" prop="speaker_subject">
            <nice-select
              v-model="teaching.speaker_subject"
              placeholder="请选择主讲科目"
              clearable
              :disabled="!isTeachingSave"
              :options="selectEnums.speaker_subject"
            ></nice-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="教师标签：" prop="label">
            <el-select
              v-model="teaching.label"
              multiple
              filterable
              allow-create
              :disabled="!isTeachingSave"
              default-first-option
              placeholder="请选择教师标签"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="简介：" prop="description">
            <el-input
              type="textarea"
              v-model="teaching.description"
              placeholder="请输入简介"
              clearable
              :disabled="!isTeachingSave"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="主讲照片：" prop="cover_head">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :disabled="!isTeachingSave"
              :http-request="uploadTeachImg"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="teaching.cover_head"
                :src="teaching.cover_head"
                class="avatar"
              />
              <i class="el-icon-plus avatar-uploader-icon" v-else></i>
              <div slot="tip" class="el-upload__tip">图片大小：238*313</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="海报信息：" prop="poster" class="clearfix">
          <el-radio-group
            v-model="teaching.poster"
            :disabled="!isTeachingSave"
            class="fl margin-right30"
          >
            <el-radio
              v-for="(poster, index) in posters"
              :label="poster.img"
              :key="index"
            >
              <img :src="poster.img" width="150" height="150" />
              <span class="el-upload-delete" @click="handleRemove(index)"
                >x</span
              >
            </el-radio>
          </el-radio-group>
          <div>
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :disabled="!isTeachingSave"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadTeacherAvatarImg"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                请上传jpg.gif.png格式的图片，建议图片宽度1096px。建议图片大小不超过5MB。
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { ossUpload, tableUpdate, tableInsert } from '@/api/api.js'
export default {
  props: {
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    teachingInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    url: '',
    staffId: ''
  },
  data () {
    return {
      posters: [],
      teaching: {
        year_of_work: '',
        speaker_rating: '',
        speaker_grade: '',
        speaker_subject: '',
        label: [],
        description: '',
        poster: '',
        cover_head: ''
      },
      isTeachingSave: false,
      teachingRules: {
        year_of_work: [
          // { required: true, message: '请输入教学经验', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^([1-9][0-9]{0,1}|99)$/.test(value) && value) {
                callback('请输入1到99之间的整数！') //eslint-disable-line
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
        // speaker_rating: [{ required: true, message: '请选择讲师评级', trigger: 'change' }],
        // speaker_grade: [{ required: true, message: '请选择主讲年级', trigger: 'change' }],
        // speaker_subject: [{ required: true, message: '请选择主讲科目', trigger: 'change' }]
      },
      options: [],
      picture: '',
      picture2: ''
    }
  },
  watch: {
    teachingInfo: {
      handler (val) {
        if (val) {
          this.posters = []
          this.isTeachingSave = false
          this.teaching.year_of_work = val.year_of_work || ''
          this.teaching.speaker_rating = val.speaker_rating || ''
          this.teaching.speaker_grade = val.speaker_grade || ''
          this.teaching.speaker_subject = val.speaker_subject || ''
          this.teaching.label = val.label ? val.label.split(',') : []
          this.teaching.description = val.description || ''
          this.teaching.poster = val.main_picture || ''
          this.teaching.cover_head = val.cover_head
          if (this.teaching.poster) {
            this.posters.push({ img: this.teaching.poster })
            val.picture && this.posters.push({ img: val.picture })
            val.picture2 && this.posters.push({ img: val.picture2 })
          }
          this.$nextTick(() => {
            this.$refs['teaching'].clearValidate()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    teachingSave () {
      if (this.isTeachingSave) {
        this.$refs['teaching'].validate(valid => {
          if (valid) {
            this.submit()
          }
        })
      } else {
        this.isTeachingSave = true
      }
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式 或 GIF 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    handleRemove (index) {
      this.posters.splice(index, 1)
      this.teaching.poster = this.posters[0].img
    },
    async submit () {
      this.picture = ''
      this.picture2 = ''
      if (this.posters && this.posters.length) {
        this.posters.forEach((ele, index) => {
          if (ele.img === this.teaching.poster) {
            if (index === 0) {
              this.picture = this.posters[1] ? this.posters[1].img : ''
              this.picture2 = this.posters[2] ? this.posters[2].img : ''
            } else if (index === 1) {
              this.picture = this.posters[0] ? this.posters[0].img : ''
              this.picture2 = this.posters[2] ? this.posters[2].img : ''
            } else {
              this.picture = this.posters[0].img || ''
              this.picture2 = this.posters[1].img || ''
            }
          }
        })
      }
      let res = this.teachingInfo.code
        ? await tableInsert([
          {
            table_name: 'nice_teacher_info',
            list: [
              {
                user_id: this.staffId,
                year_of_work: this.teaching.year_of_work,
                speaker_rating: this.teaching.speaker_rating,
                speaker_grade: this.teaching.speaker_grade,
                speaker_subject: this.teaching.speaker_subject,
                main_picture: this.teaching.poster,
                picture: this.picture,
                picture2: this.picture2,
                description: this.teaching.description,
                cover_head: this.teaching.cover_head,
                label:
                    this.teaching.label && this.teaching.label.length
                      ? this.teaching.label.join(',')
                      : ''
              }
            ]
          }
        ])
        : await tableUpdate([
          {
            table_name: 'nice_teacher_info',
            update: [
              {
                year_of_work: this.teaching.year_of_work,
                speaker_rating: this.teaching.speaker_rating,
                speaker_grade: this.teaching.speaker_grade,
                speaker_subject: this.teaching.speaker_subject,
                main_picture: this.teaching.poster,
                picture: this.picture,
                picture2: this.picture2,
                description: this.teaching.description,
                cover_head: this.teaching.cover_head,
                label:
                    this.teaching.label && this.teaching.label.length
                      ? this.teaching.label.join(',')
                      : ''
              }
            ],
            where: [
              {
                user_id: this.staffId
              }
            ]
          }
        ])
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message.success('保存成功！')
        this.isTeachingSave = false
        this.$emit('refreshData')
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async uploadTeachImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'STAFF_PORTRAIT')
      if (res[0]) {
        return
      }
      this.teaching.cover_head = res[1].data.url
    },
    async uploadTeacherAvatarImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'POSTER_COVER')
      if (res[0]) {
        return
      }
      this.posters.unshift({ img: res[1].data.url })
      if (this.posters && this.posters.length > 3) {
        this.posters.pop()
      }
      this.teaching.poster = this.posters[0].img
    }
  }
}
</script>
<style lang="scss" scoped>
.el-radio {
  position: relative;
  .el-upload-delete {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}
</style>
